<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Model\Banner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class IndexController extends Controller
{
    /**
     * 获取首页banner
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function banner(Request $request)
    {
        $banners = Banner::all();
        return JsonResponse(200,true,'获取成功',$banners);
    }

    public function banner_edit(Request $request){
        $data = $request->post();
        $data['created_at'] = strtotime($data['created_at']);
        $data['updated_at'] = time();
        $edit = Banner::where('id',$data['id'])
            ->update($data);
        if ($edit){
            return JsonResponse(200,true,'编辑成功');
        }else{
            return JsonResponse(3000,false,'编辑失败');
        }
    }

    public function banner_add(Request $request){
        $insert = $request->post();
        $insert['created_at'] = time();
        $insert['updated_at'] = time();
        $result = DB::table('banner')
            ->insert($insert);
        if ($result){
            return JsonResponse(200,true,'添加成功');
        }else{
            return JsonResponse(3000,false,'添加失败');
        }
    }

    public function banner_delete($id){
        $detail = DB::table('banner')
            ->where('id',$id)
            ->first();
        if ($detail){
            DB::beginTransaction();
            $disk = Storage::disk('local');
            $image_result = $disk->delete($detail->image_url);
            $banner_result = DB::table('banner')
                ->where('id',$id)
                ->delete();
            if ($image_result && $banner_result){
                DB::commit();
                return JsonResponse(200,true,'删除成功');
            }else{
                DB::rollBack();
                return JsonResponse(1001,false,'删除失败', $image_result, $banner_result);
            }
        }else{
            return JsonResponse(3001,false,'无此数据');
        }
    }
}
